package com.mohe.zhihui.dao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.mohe.zhihui.model.VData;

/**
 * 数据层综合实现类
 * 
 * @author dxm
 * 
 * @param <T>
 */
@SuppressWarnings("unchecked")
public class Dao<T extends VData> extends HibernateDaoSupport implements IDao<T> {

	// 要操作的数据库对象
	private Class<T> entityClass = null;

	// 日志对象
	private Log log = LogFactory.getLog(Dao.class);

	public Class<T> getEntityClass() {
		return entityClass;
	}

	public void setEntityClass(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	@Override
	public boolean insert(T t) {

		if (null == t) {
			return false;
		}

		return insert(Arrays.asList(t));
	}

	@Override
	public boolean insert(List<T> ts) {

		if (null == ts || ts.size() <= 0) {
			return false;
		}

		try {
			getHibernateTemplate().setFlushMode(HibernateTemplate.FLUSH_EAGER);
			getHibernateTemplate().saveOrUpdateAll(ts);
			getSession().clear();
			
		} catch (DataAccessException e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
			return false;
		}

		return true;
	}

	@Override
	public boolean delete(long key) {
		if (key <= 0) {
			return false;
		}

		return delete("where timeKey = ?", key);
	}

	@Override
	public boolean delete(T t) {

		if (null == t) {
			return false;
		}

		return delete(Arrays.asList(t));
	}

	@Override
	public boolean delete(List<T> ts) {

		if (null == ts || ts.size() <= 0) {
			return false;
		}

		try {
			getHibernateTemplate().setFlushMode(HibernateTemplate.FLUSH_EAGER);
			getHibernateTemplate().deleteAll(ts);
			
		} catch (DataAccessException e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
			return false;
		}
		return true;
	}

	@Override
	public boolean update(T t) {

		if (null == t) {
			return false;
		}

		return update(Arrays.asList(t));
	}

	@Override
	public boolean update(List<T> ts) {

		if (null == ts || ts.size() <= 0) {
			return false;
		}

		try {
			getHibernateTemplate().setFlushMode(HibernateTemplate.FLUSH_EAGER);
			getHibernateTemplate().saveOrUpdateAll(ts);
//			getHibernateTemplate().merge(ts);
			getSession().clear();
			
		} catch (DataAccessException e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
			return false;
		}

		return true;
	}

	@Override
	public List<Object> findBySql(String sql, List<Object> params) {

		if (null == sql || sql.trim().isEmpty()) {
			return new ArrayList<Object>();
		}

		List<Object> list = null;
		try {

			// 查询对象
			Query query = getSession().createSQLQuery(sql);
			if (null != params && params.size() > 0) {
				for (int i = 0; i < params.size(); i++) {
					query.setParameter(i, params.get(i));
				}
			}

			// 取结果
			list = query.list();

		} catch (Exception e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
		}

		return list;
	}

	@Override
	public long add(T t) {

		if (null == t) {
			return -1;
		}

		getHibernateTemplate().setFlushMode(HibernateTemplate.FLUSH_AUTO);
		long key = (Long) getHibernateTemplate().save(t);
		getSession().clear();
		
		return key;
	}

	@Override
	public T getByKey(long key) {

		if (key <= 0) {
			return null;
		}
		List<T> list = query("where timekey = ? ", Arrays.asList((Object) key));
		if (null == list || list.isEmpty()) {
			return null;
		}
		// return getHibernateTemplate().get(entityClass, key);
		
		return list.get(0);
	}

	@Override
	public List<T> query(String where, List<Object> params) {

		if (null == where || where.trim().isEmpty()) {
			return new ArrayList<T>();
		}

		List<T> list = new LinkedList<T>();
		try {

			StringBuffer hql = new StringBuffer();
			int index = where.indexOf("from");
			if (index == -1) {
				hql.append("from ");
				hql.append(entityClass.getSimpleName());
				hql.append(" ");
				hql.append(where);
			} else {
				hql.append(where);
			}

			Query query = getSession().createQuery(hql.toString());
			if (null != params && params.size() > 0) {
				for (int i = 0; i < params.size(); i++) {
					query.setParameter(i, params.get(i));
				}
			}

			// Iterator<T> ite = query.iterate();
			// while (ite.hasNext()) {
			// T t = ite.next();
			// list.add(t);
			// }
			list = query.list();
			
			
//			log.error("_______________________ wxm:" + entityClass.getName());
//			log.error("_______________________ wxm:" + hql.toString());

		} catch (Exception e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
		}
		

		return list;
	}

	@Override
	public boolean update(String set, List<Object> params) {

		if (null == set || set.trim().isEmpty()) {
			return false;
		}

		// 获取Session
		int count = 0;

		try {

			// 拼接查询语句
			StringBuffer hql = new StringBuffer();
			hql.append("update ");
			hql.append(entityClass.getSimpleName());
			hql.append(" ");
			hql.append(set);

			Query query = getSession().createQuery(hql.toString());
			if (null != params && params.size() > 0) {
				for (int i = 0; i < params.size(); i++) {
					query.setParameter(i, params.get(i));
				}
			}

			// 执行修改
			count = query.executeUpdate();
			

		} catch (Exception e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());

		}

		if (count <= 0) {

			return false;
		}

		return true;
	}

	@Override
	public boolean delete(String where, List<Object> params) {

		if (null == where || where.trim().isEmpty()) {
			return false;
		}

		int count = 0;
		try {

			// 删除语句
			StringBuffer hql = new StringBuffer();
			hql.append("delete from ");
			hql.append(entityClass.getSimpleName());
			hql.append(" ");
			hql.append(where);

			// 执行
			Query query = getSession().createQuery(hql.toString());
			if (null != params && params.size() > 0) {
				for (int i = 0; i < params.size(); i++) {
					query.setParameter(i, params.get(i));
				}
			}

			count = query.executeUpdate();
			

		} catch (Exception e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
		}

		if (count <= 0) {

			return false;
		}

		return true;
	}

	@Override
	public List<T> query(String where, int start, int count, List<Object> params) {

		if (null == where || where.trim().isEmpty()) {
			return new ArrayList<T>();
		}

		// 获取session
		List<T> list = new ArrayList<T>();
		try {

			StringBuffer hql = new StringBuffer();
			int index = where.indexOf("from");
			if (index == -1) {
				hql.append("from ");
				hql.append(entityClass.getSimpleName());
				hql.append(" ");
				hql.append(where);
			} else {
				hql.append(where);
			}

			Query query = getSession().createQuery(hql.toString());
			query.setFirstResult(start);
			query.setMaxResults(count);

			if (null != params && params.size() > 0) {
				for (int i = 0; i < params.size(); i++) {
					query.setParameter(i, params.get(i));
				}
			}

			// Iterator<T> ite = query.iterate();
			// while (ite.hasNext()) {
			//
			// T t = ite.next();
			// list.add(t);
			// }
			list = query.list();
			

		} catch (Exception e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
		}
		return list;
	}

	@Override
	public int getCount(String where, List<Object> params) {

		if (null == where || where.trim().isEmpty()) {
			return 0;
		}

		long count = 0;
		try {

			StringBuffer hql = new StringBuffer();
			hql.append("select count(*) from ");

			int index = where.indexOf("from");
			if (index == -1) {
				hql.append(entityClass.getSimpleName());
				hql.append(" ");
				hql.append(where);
			} else {
				hql.append(where.substring(index + 4));
			}

			String temp = hql.toString();
			temp = temp.replace("fetch", "");

			// 查询对象
			Query query = getSession().createQuery(temp);
			if (null != params && params.size() > 0) {
				for (int i = 0; i < params.size(); i++) {
					query.setParameter(i, params.get(i));
				}
			}

			// 取结果
			List<Object> list = query.list();
			count = (Long) list.get(0);
			
			
			log.error("_______________________ wxm:" + entityClass.getName());
			log.error("_______________________ wxm:" + hql.toString());

		} catch (Exception e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
		}

		return (int) count;
	}

	@Override
	public List<Object> findByHql(String hql, List<Object> params) {

		if (null == hql || hql.trim().isEmpty()) {
			return new ArrayList<Object>();
		}

		try {

			Query query = getSession().createQuery(hql);
			if (null != params && params.size() > 0) {
				for (int i = 0; i < params.size(); i++) {
					query.setParameter(i, params.get(i));
				}
			}

			List<Object> list = query.list();
			
			return list;

		} catch (Exception e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
		}

		return new ArrayList<Object>();
	}

	@Override
	public List<T> getAll() {

		StringBuffer hql = new StringBuffer();
		hql.append(" where isDel = 0 and timekey > -1 order by timeKey");

		return query(hql.toString(), new ArrayList<Object>());
	}

	@Override
	public List<Object> findByHql(String hql, List<Object> params, int start, int count) {

		if (null == hql || hql.trim().isEmpty()) {
			return new ArrayList<Object>();
		}

		try {

			Query query = getSession().createQuery(hql);
			if (null != params && params.size() > 0) {
				for (int i = 0; i < params.size(); i++) {
					query.setParameter(i, params.get(i));
				}
			}
			query.setFirstResult(start);
			query.setMaxResults(count);
			List<Object> list = query.list();
			
			return list;

		} catch (Exception e) {
			log.error("_______________________ rongziAssess:err:" + entityClass.getName());
			log.error("_______________________ rongziAssess:err:" + e.getMessage());
		}

		return new ArrayList<Object>();
	}

	@Override
	public boolean delete(String where, Object... params) {

		if (null == where || where.trim().isEmpty()) {
			return false;
		}

		return delete(where, Arrays.asList(params));
	}

	@Override
	public int executeHql(String hql) {
		if(hql!=null && !hql.equals("")){
			Query query = getSession().createQuery(hql);
			return query.executeUpdate();
		}
		return 0;
	}

}
